package asia.yuanding.wechat.system.util;

import asia.yuanding.wechat.web.entity.User;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: JwtUtil
 * @Author: YuanDing
 * @Date: 2025/7/26 10:07
 * @Description:
 */

@Component
@ConfigurationProperties("system.jwt")
@Data
public class JwtUtil {

    public String secret;

    public Integer expire;


    /**
     * 生成token
     * @param uid
     * @return
     */
    public String createToken(String uid) {
        // 构建payload，加入过期时间
        Map<String, Object> payload = new HashMap<>();
        payload.put("uid", uid);
        payload.put("exp", System.currentTimeMillis() / 1000 + expire); // exp单位是秒

        return JWTUtil.createToken(payload, secret.getBytes());
    }


    /**
     * 校验是否过期
     * @param token
     * @return
     */
    public boolean verifyToken(String token) {
        // 校验签名
        boolean verify = JWTUtil.verify(token, secret.getBytes());

        if (!verify) {
            return false;
        }

        // 使用JWTValidator验证时间
        try {
            JWTValidator.of(token).validateDate(); // 会抛出 ValidateException 如果过期
            return true;
        } catch (Exception e) {
           return false;
        }
    }

    public String getUId(String token) {
        // 校验签名
        boolean result = this.verifyToken(token);
        if (result) {
            JWT jwt = JWTUtil.parseToken(token);
            JWTPayload payload = jwt.getPayload();
            return payload.getClaim("uid").toString();
        }
        return null;
    }


    public User getUser(String token) {
        // 校验签名
        boolean result = this.verifyToken(token);
        if (result) {
            JWT jwt = JWTUtil.parseToken(token);
            JWTPayload payload = jwt.getPayload();
            return new User(){{setUid(payload.getClaim("uid").toString());}};
        }
        return null;
    }

}
